import finalshu.FinalShu;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 登录信息
 */
@WebServlet("/loginSrevlet")
public class LoginServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username =req.getParameter("username");
        String password = req.getParameter("password");
        if (null != username && null != password) {
            HttpSession session = req.getSession(true);
            session.setAttribute(FinalShu.FINAL_ID,username);

            //登录信息存入ServletContext，系统广播得到信息
            ServletContext sc = this.getServletContext();
            Date date = new Date();
            SimpleDateFormat ft = new SimpleDateFormat ("yyyy-MM-dd hh:mm:ss");
            Map loginList = (Map)sc.getAttribute(FinalShu.FINAL_ID_LIST);
            if (loginList ==null){
                loginList = new HashMap<>();
                loginList.put(username,ft.format(date));
            }else{
                loginList.put(username,ft.format(date));
            }
            sc.setAttribute(FinalShu.FINAL_ID_LIST,loginList);

            resp.sendRedirect("pillowTalk/PillowTalk.jsp");
        }else {
            req.getRequestDispatcher("/index.jsp").forward(req,resp);
        }
    }
}
